<?php
use lib\controller\Controller;
use lib\factory\Factory;
use lib\factory\FactoryModel;
use lib\dao\query\Query;
use lib\dao\query\QueryLimit;
use lib\dao\query\QueryLike;
use lib\dao\query\QueryAnd;

class TicketController extends Controller{
	
	public function index(){
		try{
			//$this->View->debug();
			$this->getMessages();
                        $search = $this->getParam('search');
			//Asigno resultado a la vista
			$this->View->assign('rows', $this->Model->fetch());
			
			//creo un modelo de evento
			$Eventos = Factory::create(FactoryModel::getInstance(), 'Evento');
			$this->View->assign('eventos', $this->model2List($Eventos->fetch(),'id','nombre'));

			//creo un modelo de sector
			$Sectores = Factory::create(FactoryModel::getInstance(), 'Sector');
			$this->View->assign('sectores', $this->model2List($Sectores->fetch(),'id','nombre'));

			$Q = new Query($this->Model);
                        if($search){
				$Q->add(new QueryLike('id',$search));
				//con un objeto
				/*
				$Q->add(new QueryLike(array('nombre'=>$this->getParam($search),
				'descripcion'=>$this->getParam('search'))));
				*/
			}	
			                  
                        //Asigno resultado a la vista
			$this->View->assign('rows', $this->Model->fetch());
			
						
			$P = new QueryLimit($this->getPage(),(int)$this->Config->pagination->rows);
			$Q->add($P);
			
			$Q->prepare($this->Model);	
			//$Q->dump();
			$this->View->assign('rows', $this->Model->fetch($Q));
			$this->View->assign('P', $P);
			$this->View->assign('page', $this->getPage());
			$this->View->assign('search', $search);
			//Muestro template
			$this->View->display();
		}
		catch (\Exception $e){
			die($e->getMessage());
		}	
	}

	public function compra(){
		try{
			$this->View->layout = 'frontend';
			
			$id = $this->getParam('ticket');
			if(empty($id))
				throw new \Exception('No se puede continuar sin ID');

		//Carga el ticket que viene por parametro
			$Q2 = new Query($this->Model);
			$Q2->add(new QueryAnd('id',$id));
			if(!$this->Model->load($Q2)){
				throw new \Exception('No exite tickets para esta compra');
			}

		
			$this->View->assign('tickets',$this->Model->toArray($this->Model));

			$Q3 = new Query(Factory::create(FactoryModel::getInstance(), 'Sector'));
			if(!$sectores=($this->Model->fetch($Q3))){
				 throw new \Exception('No existe sectores para esta compra');
			}

			$this->View->assign('sectores',$sectores);

			$Eventos = Factory::create(FactoryModel::getInstance(), 'Evento');
			$this->View->assign('eventos', $this->model2List($Eventos->fetch(),'id','nombre'));

			$Lugares = Factory::create(FactoryModel::getInstance(), 'Lugar');
			$this->View->assign('lugares', $this->model2List($Lugares->fetch(),'id','nombre'));

			
		}catch (\Exception $e){
			$this->View->assign('msg', array('error',$e->getMessage()));
		}
		$this->View->display();
	}
	
	public function crear(){
		try{
		//hidden o tomar valor del boton submit para saber si
		//postearon formulario.
			$do_submit = $this->getParam('do_submit');
			$evento = $this->getParam('evento_id');
			$sector = $this->getParam('sector_id');
			
		//creo un modelo de evento
			$Eventos = Factory::create(FactoryModel::getInstance(), 'Evento');
			$this->View->assign('eventos', $this->model2List($Eventos->fetch(),'id','nombre'));

		//Cargo los sectores para el evento
			if(!empty($evento)){
			
		//Obtenemos el id_lugar del evento
				$Q2 = new Query($Eventos);		
				$Q2->add(new QueryAnd('id',$evento));
				if(!$Eventos->load($Q2))
					throw new Exception("No hay lugar para ese evento");
                                
                //cargo el lugar usando el lugar_id de evento                
                                $Lugares = Factory::create(FactoryModel::getInstance(), 'Lugar');
                                $Q3 = new Query($Lugares);
                                $Q3->add(new QueryAnd('id', $Eventos->lugar_id));
                                $Lugares->load($Q3);
                               
                                $this->View->assign('lugares', $Lugares->toArray());
					
		//creo un modelo de sector
				$Sectores = Factory::create(FactoryModel::getInstance(), 'Sector');
				$Q = new Query($Sectores);
				$Q->add(new QueryAnd('lugar_id',$Eventos->lugar_id));
				$this->View->assign('sectores', $this->model2List($this->Model->fetch($Q),'id','nombre'));
			}	

				
	
                        
                        
			
            if($do_submit){
			
			//cargo modelo con parametros del form
				$this->params2Model($this->Model);

			//Recargo solo para cargar combo sectores
				if(!empty($evento) && !empty($sector)){
					//campos obligatorios
					$this->required($this->Model, array('precio'));

					//invoco create heredado de Model
					$this->Model->create();
					$this->clean($this->Model);
					$this->View->assign('msg', array('success', 'El registro se ha guardado correctamente'));	
				}				
				
			}
		}
		catch (\Exception $e){
			$this->View->assign('msg', array('error',$e->getMessage()));
		}
		$this->View->assign('model', $this->Model->toArray());
		$this->View->display();	
	}
	
	public function eliminar(){		
			$id = $this->getParam('id');	
                        $Q= new Query($this->Model);
			$Q->add(new QueryAnd('id',$id));
			if(empty($id)){
				header("location: /ticket/index/status/1/");
				exit();
			}
				
			$this->Model->id = $id;
			if(!$this->Model->load($Q)){
				header("location: /ticket/index/status/2/");
				exit();
			}
			
			$this->Model->delete();
			header("location: /ticket/index/status/0/");
			exit();			
	}
	
	public function actualizar(){
		try{
			//hidden o tomar valor del boton submit para saber si
			//postearon formulario.
			$do_submit 	= $this->getParam('do_submit');
			$id 		= $this->getParam('id');
			
			if(empty($id)){
				throw new \Exception('No es posible continuar sin identificador');
			}
			
			$this->Model->id = $id;
			$Q= new Query($this->Model);
			$Q->add(new QueryAnd('id',$id));
			if(!$this->Model->load($Q)){
				throw new \Exception('Identificador no valido');
			}
			
			//creo un modelo de ticket
			$Eventos = Factory::create(FactoryModel::getInstance(), 'Evento');
			$this->View->assign('eventos', $this->model2List($Eventos->fetch(),'id','nombre'));

			//creo un modelo de sector
			$Sectores = Factory::create(FactoryModel::getInstance(), 'Sector');
			$this->View->assign('sectores', $this->model2List($Sectores->fetch(),'id','nombre'));
				
				
			
			
			if($do_submit){
				//cargo modelo con parametros del form
				$this->params2Model($this->Model);
				//campos obligatorios
				$this->required($this->Model, array('precio'));
				//invoco update heredado de Model
				$this->Model->update();
				$this->View->assign('msg', array('success', 'El registro se ha actualizado correctamente'));
			}
		}
		catch (\Exception $e){
			$this->View->assign('msg', array('error',$e->getMessage()));
		}
		$this->View->assign('id', $id);
		$this->View->assign('model', $this->Model->toArray());
		$this->View->display();
	}
}